<template>
  <div class="calendar-wrapper">
    <!-- 日历组件 -->
    <el-card class="calendar-card" shadow="hover" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>服务日历</span>
          <div class="calendar-actions">
            <el-button-group>
              <el-button size="small" @click="prevMonth">
                <el-icon name="ArrowLeft"></el-icon>
              </el-button>
              <el-button size="small" @click="nextMonth">
                <el-icon name="ArrowRight"></el-icon>
              </el-button>
              <el-button size="small" @click="goToday">今天</el-button>
            </el-button-group>
            <span class="current-month">{{ currentMonth }}</span>
          </div>
        </div>
      </template>

      <el-calendar v-model="currentDate" class="custom-calendar">
        <template #date-cell="{ data }">
          <div
              class="calendar-day"
              :class="{
              today: isToday(data.day),
              'has-appointment': hasAppointment(data.day),
              'selected-date': selectedDate === data.day
            }"
              @click="showAppointmentsForDate(data.day)"
          >
            <span :class="{
              'today-text': isToday(data.day),
              'selected-text': selectedDate === data.day
            }">
              {{ data.day.split('-').slice(2).join('-') }}
            </span>
            <div v-if="hasAppointment(data.day)" class="appointment-dot"></div>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <!-- 显示当前选中日期的预约信息 -->
    <el-card v-if="selectedDateAppointments.length > 0" class="appointments-list-card" shadow="hover">
      <template #header>
        <span>{{ selectedDate }} 的预约信息</span>
      </template>
      <ul class="appointment-list">
        <li v-for="app in selectedDateAppointments" :key="app.id" class="appointment-item">
          <strong>编号：{{ app.id }}</strong><br/>
          <small>时间：{{ formatTime(app.appointmentTime) }}</small><br/>
          <small>联系人：{{ app.contactName }} - {{ app.contactPhone }}</small><br/>
          <el-button size="mini" type="primary" @click="openAppointmentDetail(app.id)">查看详情</el-button>
        </li>
      </ul>
    </el-card>

    <div v-else class="no-data">
      <p v-if="!appointments.length">暂无预约信息</p>
      <p v-else-if="selectedDate">暂无预约信息</p>
    </div>
  </div>

  <!-- 弹窗组件 -->
  <AppointmentDetailDialog
      v-model:visible="showDetailDialog"
      :appointment-id="selectedAppointmentId"
  />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from '@/request/request.js'
import { useRouter } from 'vue-router'
import AppointmentDetailDialog from '@/views/escort/AppointmentDetail.vue'

const router = useRouter()

// 当前日期
const currentDate = ref(new Date())

// 所有预约数据
const appointments = ref([])

// 当前选中的日期及对应预约
const selectedDate = ref('')
const selectedDateAppointments = ref([])
const loading = ref(false)

// 控制弹窗显示和ID
const showDetailDialog = ref(false)
const selectedAppointmentId = ref(null)

// 获取当前月份
const currentMonth = computed(() => {
  if (!currentDate.value) return ''
  return currentDate.value.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long'
  })
})

// 判断是否是今天
const isToday = (dateStr) => {
  const today = new Date()
  const date = new Date(dateStr)
  return (
      date.getDate() === today.getDate() &&
      date.getMonth() === today.getMonth() &&
      date.getFullYear() === today.getFullYear()
  )
}

// 判断是否有预约
const hasAppointment = (dateStr) => {
  const targetDate = dateStr.split(' ')[0]
  return appointments.value.some(app => {
    const appDate = new Date(app.appointmentTime).toISOString().split('T')[0]
    return appDate === targetDate
  })
}

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleString()
}

// 点击切换上个月
const prevMonth = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() - 1)
  currentDate.value = newDate
  fetchAppointments()
}

// 点击切换下个月
const nextMonth = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() + 1)
  currentDate.value = newDate
  fetchAppointments()
}

// 跳转到今天
const goToday = () => {
  currentDate.value = new Date()
  fetchAppointments()
}

// 获取指定日期的预约数据
const showAppointmentsForDate = async (dateStr) => {
  console.log('Clicked date:', dateStr); // 调试信息
  const targetDate = dateStr.split(' ')[0] // YYYY-MM-DD
  selectedDate.value = targetDate

  try {
    loading.value = true
    const params = {
      date: targetDate
    }
    const res = await axios.get('/v1/escort/appointmentdetail', { params, withCredentials: true })
    console.log('返回的信息是: ', targetDate, ':', res.data); //
    if (res.data.state === 2000) {
      selectedDateAppointments.value = res.data.data.map(app => ({
        ...app,
        appointmentTime: new Date(app.appointmentTime)
      }))
      console.log('查询到的预约信息是:', selectedDateAppointments);
    } else {
      // console.error('获取预约数据失败:', res.data.message)
      selectedDateAppointments.value = []
    }
  } catch (error) {
    console.error('请求出错:', error)
    selectedDateAppointments.value = []
  } finally {
    loading.value = false
  }
}

// 获取预约数据
const fetchAppointments = async () => {
  loading.value = true
  try {
    const params = {
      month: currentDate.value.getMonth() + 1,
      year: currentDate.value.getFullYear()
    }

    console.log('请求参数:', params)
    const res = await axios.get('/v1/escort/appointmentdetail', { params, withCredentials: true })

    if (res.data.state === 2000) {
      console.log('响应数据:', res.data.data)
      appointments.value = res.data.data.map(app => ({
        ...app,
        appointmentTime: new Date(app.appointmentTime)
      }));
      // 默认选中今天
      const todayStr = new Date().toISOString().split('T')[0]
      selectedDate.value = todayStr
      showAppointmentsForDate(todayStr)
    } else {
      // console.error('获取预约数据失败:', res.data.message)
    }
  } catch (error) {
    console.error('请求出错:', error)
  } finally {
    loading.value = false
  }
}

// 打开预约详情弹窗
const openAppointmentDetail = (id) => {
  if (!id) {
    console.warn('无效的预约ID')
    return
  }
  selectedAppointmentId.value = id
  showDetailDialog.value = true
}

onMounted(() => {
  fetchAppointments().then(() => {
    // 获取今天的日期字符串
    const todayStr = new Date().toISOString().split('T')[0];
    // 显示今天的预约信息
    showAppointmentsForDate(todayStr);
  });
})

</script>

<style scoped>
.calendar-wrapper {
  padding: 20px;
  background-color: #f0f9ff; /* 与 #c4e2fb 相近的浅色调作为背景 */
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.calendar-card {
  margin-bottom: 20px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(196, 226, 251, 0.4); /* 使用 #c4e2fb 作为阴影色调来源 */
}

.calendar-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.current-month {
  font-size: 18px;
  font-weight: bold;
  margin-left: 10px;
  color: #333;
}

.custom-calendar .el-calendar-table thead th {
  color: #409eff;
  font-weight: bold;
}

.calendar-day {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  font-size: 14px;
  transition: background-color 0.2s ease; /* 添加过渡效果 */
}

.calendar-day:hover {
  background-color: #e6f2ff; /* 鼠标悬停时的背景色 */
}

.calendar-day.today {
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.appointment-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #409eff;
  margin-top: 2px;
}

.appointments-list-card {
  margin-top: 20px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(196, 226, 251, 0.4);
}


.appointment-list {
  list-style: none;
  padding-left: 0;
}

.appointment-item {
  padding: 12px;
  border-bottom: 1px solid  #e6f2ff;
}

.appointment-item:last-child {
  border-bottom: none;
}

.no-data {
  text-align: center;
  color: #999;
  margin-top: 10px;
}

.today .today-text {
  color: white;
  font-weight: bold;
  background-color: #409eff;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
}

.selected-date .selected-text {
  color: #ff9900;
  font-weight: bold;
  border-bottom: 2px solid #ff9900;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 8px;
  padding: 6px 12px;
  transition: background-color 0.2s ease, transform 0.2s ease;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #3584e4;
  transform: translateY(-2px);
}

.el-button--small {
  padding: 4px 8px;}
</style>

